from decimal import Decimal
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection

# Create your views here.

from goods.models import SKU
from orders.serailizers import OrderSKUSerializer


# GET /orders/settlement/
# 订单信息显示
class OrderSettlementView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        '''
        1. 获取用户勾选的商品的id以及数量
        2. 根据商品id获取商品的数据和对应的运费
        3. 将商品数据序列化返回
        '''
        # 1. 获取用户勾选的商品的id以及数量
        # 1. 从redis中获取勾选的商品id\
        user = request.user
        redis_conn = get_redis_connection('cart')
        cart_selected_key = 'cart_selected_%s' % user.id

        sku_ids = redis_conn.smembers(cart_selected_key)
        # 拿到hash所有的商品
        cart_key = 'cart_%s' % user.id
        cart_redis = redis_conn.hgetall(cart_key)

        # 2. 获取商品id对应的数量

        cart_dict = {}
        # 将redis中取出数据转化为int类型
        for sku_id, count in cart_redis.items():
            cart_dict[int(sku_id)] = int(count)

        # 2. 根据商品id获取商品的数据和对应的运费
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            sku.count = cart_dict[sku.id]

        # 组织运费
        freight = Decimal(10)

        # 3. 将商品数据序列化返回
        serializer = OrderSKUSerializer(skus, many=True)
        data = {
            'freight': freight,
            'skus': serializer.data
        }
        return Response(data=data)
